#include "server_protect.h"
static unsigned int remoteFileProtection(rawPacket_t* packet){
	char text_len[LENGTH_SIZE+1] = {0}; 
	int i, length;
	char *p;
	//char cmd;
	msg_t command = {0};
	if(packet->dest_port != REMOTE_FILE_STANDARD_PORT)
		return NF_ACCEPT;
	
	if(packet->data_length  == 0)
		return NF_ACCEPT;
	memcpy(&command,packet->data,MSG_SIZE);
	
	//cmd = packet->data[0];
	//printk("\n* command: %c \n",command.cmd);	
	switch(command.cmd){
		
		case CMD_CLEAR:	
		case CMD_RESET:
		case CMD_READ:
			if(packet->data_length > SHORT_CMD_LENGTH + NEW_LINE_LEN){
				//printk("\n* data length to long for clear/reset/read \n");
				return NF_DROP;
			}
			if(packet->data_length == SHORT_CMD_LENGTH + NEW_LINE_LEN && (packet->data[1]!='\n' && packet->data[1]!='\r')){
				//printk("\n* clear/reset/read has additional chars at the end \n");
				return NF_DROP;
			}
			return NF_ACCEPT;	
			break;
			
		case CMD_APPEND:
		case CMD_WRITE:
			if(packet->data_length < MIN_LONG_CMD_LENGTH){
				//printk("\n* append/write command to short \n");
				return NF_DROP;
			}
			if(packet->data_length > LONG_CMD_LENGTH + NEW_LINE_LEN){
				//printk("\n* append/write command to long \n");
				return NF_DROP;
			}
			if(packet->data_length == LONG_CMD_LENGTH + NEW_LINE_LEN && (packet->data[LONG_CMD_LENGTH]!='\n' && packet->data[LONG_CMD_LENGTH]!='\r')){
				//printk("\n* append/write has additional chars at the end \n");
				return NF_DROP;	 
			}
				
			// check length			
			for(i=1;i<=LENGTH_SIZE && i<packet->data_length;++i){
				if(packet->data[i] < '0' || packet->data[i] > '9')
					break;
				else
					text_len[i-1] = packet->data[i];
			}
			
			if(i == 1){
				//printk("\n* append/write command has no data length \n");
				return NF_DROP; // no length in command				
			}
			
			//memcpy(text_len, command.len, LENGTH_SIZE);
			text_len[LENGTH_SIZE] = (char)0;					
			p = (char *)text_len;	
			length = simple_strtoul(p,&p,10);
			//printk("\n* data length:%s-%d \n",text_len,length);
			if (!p || (*p && (*p != '\n'))){
				//printk("\n* append/write command data length incorrect : %s -  %d\n",command.len,length);
				return NF_DROP;		
			}
			
			if(length > SRV_BUFFER_MAX_SIZE){
				//printk("\n* append/write command data length to big \n");
				return NF_DROP;	 // buffer overflow !!!
			}				
			
			return NF_ACCEPT;	
			break;
			
		default:
				return NF_DROP; // not in protocol
	}	
}
